## usage: id = nc2date (ncfile, tvar, varargin)
##
## read netcdf time coordinate
function [id err] = nc2date (ncfile, tvar, varargin)

   pkg load netcdf

   if nargin < 2, tvar = "time" ; endif
   
   err = isempty(cell2mat(strfind({ncinfo(ncfile).Variables.Name}, tvar))) ;
   if err
      id = NaN ;
      return ;
   endif
      
   wtime = ncread(ncfile, tvar, varargin{:}) ;
   wstr = strsplit(ncreadatt(ncfile, tvar, "units"), " ", STRIP_EMPTY=true) ;
   try
      wcal = ncreadatt(ncfile, tvar, "calendar") ;
   catch
      wcal = "gregorian" ;
   end_try_catch
   
   if strcmp(wstr(1){:}, "hours")
      wq = 24 ;
   else
      wq = 1 ;
   endif

   if strcmp(wstr(2){:}, "since")
      d0 = [sscanf(wstr(3){:}, "%d-%d-%d"); 0]' ;
      if (strcmp(wcal, "gregorian") || strcmp(wcal, "standard")) && date_cmp(d0(1:3), [1582 10 14])
	 jd = wtime/wq - 2 ;
      else
	 jd = wtime/wq ;
      endif
      j0 = date2cal(d0, wcal) ;
      [id(:,1), id(:,2), id(:,3), id(:,4)] = cal2date(j0 + jd, wcal) ;
   else
      id = dat(nc{tvar}(:)) ;
   endif

   id = double(id) ;

endfunction
